const app = getApp();

Page({
  data: {
    selectedPlan: 'month',
    purchasing: false
  },

  // 选择套餐
  selectPlan(e) {
    const plan = e.currentTarget.dataset.plan;
    this.setData({
      selectedPlan: plan
    });
  },

  // 购买会员
  purchaseMembership() {
    if (!app.globalData.isLogin) {
      wx.showModal({
        title: '提示',
        content: '请先登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/register/register'
            });
          }
        }
      });
      return;
    }

    this.setData({
      purchasing: true
    });

    // 模拟支付流程
    setTimeout(() => {
      // 更新会员状态
      const expireTime = this.calculateExpireTime();
      app.globalData.isMember = true;
      app.globalData.memberExpireTime = expireTime;
      
      if (app.globalData.userInfo) {
        app.globalData.userInfo.isMember = true;
        app.globalData.userInfo.memberExpireTime = expireTime;
        wx.setStorageSync('userInfo', app.globalData.userInfo);
      }

      this.setData({
        purchasing: false
      });

      wx.showToast({
        title: '购买成功',
        icon: 'success'
      });

      // 返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }, 2000);
  },

  // 计算到期时间
  calculateExpireTime() {
    const now = new Date();
    let expireDate;
    
    switch (this.data.selectedPlan) {
      case 'month':
        expireDate = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate());
        break;
      case 'quarter':
        expireDate = new Date(now.getFullYear(), now.getMonth() + 3, now.getDate());
        break;
      case 'year':
        expireDate = new Date(now.getFullYear() + 1, now.getMonth(), now.getDate());
        break;
      default:
        expireDate = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate());
    }
    
    return expireDate.toLocaleDateString('zh-CN');
  }
}); 